package com.cc8w.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cc8w.entity.UserPojo;
import com.cc8w.util.RequestData;

@Controller
@RequestMapping("/home/test")
public class TestController extends BaseController  {
	
	@ModelAttribute("init")
	public String Init(HttpServletRequest request) {
		System.out.println("TestController每次请求都执行");
		//当前项目下路径
        File file = new File("");
        String filePath;
		try {
			filePath = file.getCanonicalPath();
			System.out.println(filePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
 
        //当前项目下xml文件夹
        File file1 = new File("");
        String filePath1;
		try {
			filePath1 = file1.getCanonicalPath()+File.separator+"xml\\";
			System.out.println(filePath1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
 
        //获取类加载的根路径
        File file3 = new File(this.getClass().getResource("/").getPath());
        System.out.println(file3);
 
        //获取当前类的所在工程路径
        File file4 = new File(this.getClass().getResource("").getPath());
        System.out.println(file4);
 
        //获取所有的类路径 包括jar包的路径
        System.out.println(System.getProperty("java.class.path"));
        
        //Spring工具类获取项目路径
        String filePath2 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        System.out.println(filePath2);
		
        //项目路径
        String filePath3 = request.getServletContext().getRealPath("/");
        System.out.println(filePath3);
        
        
		return "";
	}
	
	/**
	 * test首页方法  
	 */
	@RequestMapping("/index")
	public String index() {
		
		HttpServletRequest req = this.request;
		HttpServletResponse resp= this.response;
		System.out.println(req);
		System.out.println(resp);
		System.out.println("home/test/index");
		
        this.model.addAttribute("user", "123");
        return "home/test/index";		
	}
	
	/**
	 * test--form  
	 */
	@RequestMapping("/form1")
	public String form1() {
		
		HttpServletRequest req = this.request;
		HttpServletResponse resp= this.response;
		
		RequestData rd =null;
		try {
			rd = new RequestData(request);
		} catch (IOException | DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String req_data = JSON.toJSONString(rd);
		this.model.addAttribute("pageData", rd);
		this.model.addAttribute("req_data", req_data);
		
        this.model.addAttribute("user", "123");
        return "home/test/form1";		
	}
	
	/**
	 * 在test中测试文件上传
	 * @throws FileUploadException 
	 * @throws DocumentException 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@ResponseBody
	@RequestMapping("/upload")
	public String upload() throws FileUploadException, IOException, DocumentException, ServletException {
		
		//文档：http://commons.apache.org/proper/commons-fileupload/
		boolean isMultipart =  ServletFileUpload.isMultipartContent(this.request);
		
		//表单的文件上传提交 enctype="multipart/form-data"
		if(isMultipart) {
			//FileItemFactory是一个接口，所以只能实例化其实现类
			//(可以设置用户提交的二进制数据编码,和临时存放目录)
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload  upload =  new ServletFileUpload(factory);
			//通过parseRequest解析form中所有的请求字段，保存到items集合中
			List<FileItem> items = upload.parseRequest(this.request);
			System.out.println(items.size());
			
			Iterator<FileItem> iter=  items.iterator();

			while(iter.hasNext()) {
				FileItem fi = iter.next();
				if(fi.isFormField()) {
				    String name = fi.getFieldName();
				    String value = fi.getString();
				    System.out.println(name+"--->"+value);
				}else {
					//文件字段
				    String fieldName = fi.getFieldName();
				    String fileName = fi.getName();
				    String contentType = fi.getContentType();
				    boolean isInMemory = fi.isInMemory();
				    long sizeInBytes = fi.getSize();

				    System.out.println(fieldName+"->"+fileName+"->"+contentType+"->"+isInMemory+"->"+sizeInBytes);
				   
				    
				    String uploadPath = this.getClass().getResource("").getPath();
				    
				    //File uploadedFile = new File(uploadPath+"../../../../../uploads/"+fileName);
				    File uploadedFile = new File(uploadPath+"../../../../../uploads/"+fileName+"11.txt");
				    FileUtils.copyInputStreamToFile(fi.getInputStream(), uploadedFile);
				    
//				    try {
//						fi.write(uploadedFile);
//					} catch (Exception e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}finally {
//						
//					}			
					
				    
				}
				
			}
			
			
//			Map<String, List<FileItem>> pm = upload.parseParameterMap(this.request);
//			String pms = JSON.toJSONString(pm);
//			System.out.println(pms);
			
		}

		
		
		
		UserPojo up = new UserPojo(1,"name11",1);
		String data = JSON.toJSONString(up);
		return data;		
	}
	
	

}
